<html>

<!-- Mirrored from bos.asmhackers.net/docs/booting/docs/tutorial_04.htm by HTTrack Website Copier/3.x [XR&CO'2013], Tue, 07 Oct 2014 11:22:01 GMT -->
<head>
	<script type="text/javascript">
		if (screen.height < 768) {
			document.write('<link rel="stylesheet" type="text/css" href="../../main_lores.html" />');
		}
		else {
			document.write('<link rel="stylesheet" type="text/css" href="../../main.html" />');
		}
	</script>
</head>
<body margin-left=180px>
	<h1>Getting keyboard response</h1><br>

	<h2 class="header">Interrupts?! I hate to be interrupted!</h2>

	<h2>So far, we managed to clear the screen from all the nonsense that is there when we start our computer or emulator. We've also learned how to make beautiful little characters appear where we want them to. Everything we've done has been static or predetermined. In a real OS, you can move the mouse or press some keys and hopefully make something happen. We want that in our OS as well :). This tutorial with teach you how to interact with one of the computer's oldest accessories - the keyboard.<br><br>

	If you already know what an interrupt in computer terms is, you can jump to the next section. I don't tolerate people sitting here getting bored, they can read some other tutorials! ;)<br><br>

	As far as I know, there are two ways to get the CPU to know what's happening outside it's little world. Either it asks every device if something has happened (this method is called polling), or the devices is letting the CPU know when something has happened (interrupt based communication). Asking takes resources from the CPU, so if we let the devices shout instead of answering letters, it would release the CPU from writing the letters and just answer the calls instead. Very convenient and effective!<br><br>

	An interrupt is simply what the name says. It interrupts the CPU. There are two types, internal and external. The internal interrupt is accually a program asking for a service by the Operating System or the BIOS. Something it can't do by itself, like reading from a disk. An external interrupt is related to physical little connections to the CPU that indicates that something needs or <i>should</i> be done. A perfect example for our little tutorial is the keyboard. Every time you press a key, it sends an electronic signal to the motherboard that forwards the signal to the PIC (<i>Programmable Interrupt Controller</i>).<br><br>

	As the name says, it can be programmed to do things. Not very much, but still :). It's actually just a mask for the interrupts. Any interrupts that comes to the PIC, is simply run through the mask and if it passes, the signal is sent to the CPU and the code running at the moment is interrupted. The CPU saves its present state and looks in a little thing called the <i>interrupt table</i> or the <i>interrupt vector</i>. Say the CPU received interrupt 34. Then it looks at offset 34 in the interrupt table and sees there an address which it jumps to. This is the interrupt routine. It's usually very short. A keyboard interrupt for example, could read the key value, save it in a buffer and end. Short and simple! After an interrupt is finished, the CPU restores the pre-interrupt state and continues to execute the code like nothing ever happened!<br></h2>

	<h2 class="header">And now for some acual coding!</h2>

	<h2>As always before, we start with the boot sector. We first tell the compiler that we are writing 16-bit instructions and start at address 0x7C00. Then we read a number of sectors from the disk to memory address 0x1000. After that we just fill in the GDT and jump to our main() function. If you don't know the following piece of code, please look at my <a href="../tutorial_03/tutorial_03.html">previous tutorial</a>.</h2>

		<h4>[BITS 16]<br><br>
		[ORG 0x7C00]</h4>

		<h4>reset_drive:</h4>
			<h5>mov ah, 0<br>
			int 13h<br>
			or ah, ah<br>
			jnz reset_drive<br><br>

			mov ax, 0<br>
			mov es, ax<br>
			mov bx, 0x1000<br><br>

			mov ah, 02h<br>
			mov al, 02h<br>
			mov ch, 0<br>
			mov cl, 02h<br>
			mov dh, 0<br>
			int 13h<br>
			or ah, ah<br>
			jnz reset_drive</h5>

			<h5>cli<br>
			xor ax, ax<br>
			mov ds, ax<br><br>
			lgdt [gdt_desc]<br>
			mov eax, cr0<br>
			or eax, 1<br>
			mov cr0, eax<br>
			jmp 08h:clear_pipe</h5><br>

		<h4>[BITS 32]<br>
		clear_pipe:</h4>
			<h5>mov ax, 10h<br>
			mov ds, ax<br>
			mov ss, ax<br>
			mov esp, 090000h<br>
			mov 08h:01000h</h5>

	<h2>In the previous tutorial, we had three segments in the GDT: null, code and data. Now we need to add another that should hold our interrupt code. This segment should start at address 0x1000, because when we fill the interrupt table, the addresses are relative. So the new entry is almost a copy of the first code entry, except the memory address. The GDT should look like this:</h2>

		<h4>gdt:<br><br>
		gdt_null:</h4>
			<h5>dd 0<br>
			dd 0</h5><br>

		<h4>gdt_code:</h4>
			<h5>dw 0FFFFh<br>
			dw 0<br>
			db 0<br>
			db 10011010b<br>
			db 11001111b<br>
			db 0</h5><br>

		<h4>gdt_data:</h4>
			<h5>dw 0FFFFh<br>
			dw 0<br>
			db 0<br>
			db 10010010b<br>
			db 11001111b<br>
			db 0</h5><br>

		<h4>gdt_interrupts:</h4>
			<h5>dw 0FFFFh<br>
			dw 01000h<br>
			db 0<br>
			db 10011010b<br>
			db 11001111b<br>
			db 0</h5><br>

		<h4>gdt_end:<br><br>
		gdt_desc:</h4>
			<h5>dw gdt_end - gdt - 1<br>
			dd gdt</h5><br>

	<h2>Don't forget to fill up the boot sector!</h2>

		<h4>times 510-($-$$) db 0</h4>
			<h5>dw 0AA55h</h5>

	<h2>All this should be saved into a .asm file. I call mine <i>bootsect.asm</i>. Then it's time for jumping to C and main(). The function is plain and simple. Just two function calls and an infinite loop.</h2>

		<h4>void main()<br>
		{</h4>
			<h5>clrscr();<br>
			init_interrupts();<br>
			for(;;);</h5>
		<h4>}</h4>

	<h2>If you remember, we've already written clrsrc(). This was done in the <a href="../tutorial_03/tutorial_03.html">tutorial 3</a>. The main focus of this tutorial is coming up, init_interrupts()!</h2>

	<h2 class="header">The main event of tutorial 4</h1>

	<h2>To set up interrupts, we will need to fill in the <i>IDT</i> or the <i>Interrupt Descriptor Table</i>. It basically wants to know where to jump when a special interrupt occurs. Interrupts have numbers. The first 20 interrupts are hardware interrupts in the CPU. They are related to faults that can occur when executing code. After the 20 reserved interrupts, there comes another 12 interrupts that are reserved by Intel. Nobody knows if something exists there or what they might do, but you shouldn't touch them. So, our first interrupt should be placed at index 32 (starting with 0) in the IDT.<br><br>

	<table border=1>
		<tr>
			<th>Interrupt</th><th>Description</th>
		</tr><tr>
			<td>0</td><td>Divide by Zero</td>
		</tr><tr>
			<td>1</td><td>Debug: Trap</td>
		</tr><tr>
			<td>2</td><td>Nonmaskable external interrupt</td>
		</tr><tr>
			<td>3</td><td>Debug: Breakpoint</td>
		</tr><tr>
			<td>4</td><td>Overflow</td>
		</tr><tr>
			<td>5</td><td>BOUND range exceeded(?)</td>
		</tr><tr>
			<td>6</td><td>Invalid opcode</td>
		</tr><tr>
			<td>7</td><td>No Math Cooprocessor (when trying to use it)</td>
		</tr><tr>
			<td>8</td><td>Double fault (something went terrably wrong!)</td>
		</tr><tr>
			<td>9</td><td>Cooprocessor segment overrun(?)</td>
		</tr><tr>
			<td>10</td><td>Invalid Task switch</td>
		</tr><tr>
			<td>11</td><td>Memory: Segment not present</td>
		</tr><tr>
			<td>12</td><td>Memory: Stack-segment fault</td>
		</tr><tr>
			<td>13</td><td>Memory: General protection</td>
		</tr><tr>
			<td>14</td><td>Memory: Page fault</td>
		</tr><tr>
			<td>15</td><td>Reserved by Intel</td>
		</tr><tr>
			<td>16</td><td>FPU error or WAIT/FWAIT instruction</td>
		</tr><tr>
			<td>17</td><td>Memory: Alignment check</td>
		</tr><tr>
			<td>18</td><td>Machine Check(?)</td>
		</tr><tr>
			<td>19</td><td>SSE/SSE2-Exception</td>
		</tr><tr>
			<td>20-31</td><td>Reserved by Intel</td>
		</tr><tr>
			<td>32-255</td><td><i>Available to the programmer!</i></td>
		</tr>
	</table><br>

	First, fire up your favourite text editor and create a new file. An entry in the IDT is 64 bits long. Because the largest integer we can have is 32 bit long, we need to create a struct for our entry. This is simply just two unsigned longs.</h2>

		<h4>typedef struct {</h4>
			<h5>unsigned long dword0;<br>
			unsigned long dword1;</h5>
		<h4>} segment_desc;</h4>

	<h2>Before we begin setting up interrupts, we need a function to take care of the call. We'll write this later, for now we just declare it.</h2>

		<h4>extern void keyb_int();</h4>

	<h2>Then we define the init_interrupts()-function we call from main()...</h2>

		<h4>void init_interrupts()<br>
		{</h4>

	<h2>...and define some local variables.</h2>

			<h5>segment_desc idt[0x100];<br>
			unsigned long idt_desc[2];<br>
			unsigned long idt_address;<br>
			unsigned long keyb_address;</h5>

	<h2>A short explaination of the variables. The <i>idt</i> structure contains the addresses to the interrupt routines (we only have one, but the IDT must be filled to at least 0x21 where our keyboard interrupt lays, but I've set it to maximum size, 256). To make the CPU find the IDT, we must also have a variable and that's what <i>idt_desc</i> is there for. Both <i>idt_address</i> and <i>keyb_address</i> are simply helping variables (you'll understand later).<br><br>

	Now... To get interrupts up and running we first need to program the PIC to redirect the hardware interrupts to the right place. This is done through ports 0x20-0x21 and 0xA0-0xA1. There's acually two PICs (one master and one slave) and each one can handle eight interrupts. There are newer versions on modern hardware called APIC (<i>Advanced Programmable Interrupt Controller</i>), but it's backwards compatible, so this should run on older hardware as well.<br><br>

	The first words sent to the ports are called ICWs (<i>Interrupt Control Words</i>). This is kind of much to explain, but I'll try. There are at least two controll words you can send and at maximum four. How many is dicided in the first ICW as follows.<br><br>

	The LSB (<i><b>L</b>east <b>S</b>ignificant <b>B</b>it</i>) controls whether there is fourth ICW or not. In our case, yes, so this should be set. The next bit controls whether there are one or two PICs available and hence a third ICW. This should not be set in our case, specifying <i>two</i> PICs. The two next bits should be set to 0. They control stuff that I don't really know :) and specifying that the interrupts is edge triggered instead of level triggered. If you really care about the difference, make a search on <a href="http://www.google.com/" target="_blank">Google</a> or something. The fifth bit (bit 4), should be set, telling the PIC that this is the ICW1. The last three bits should be ignored and set to 0. We send the same ICW1 to both the PICs.</h2>

		<h5>out(0x20, 0x11);<br>
		out(0xA0, 0x11);</h5>

	<h2>The first ICW is always sent to port 0x20. All the other ICWs are instead sent to 0x21 and 0xA1, just for the record. The second ICW is straight forward. It tells the PICs what interrupt they should begin raising on the different pins. Each PIC had eight interrupt pins, as I wrote before. Our first interrupt we can program is 0x20, so we send this value to the first PIC. Because it occupies eight interrupts, the second one gets interrupts 0x28-0x2F.</h2>

		<h5>out(0x21, 0x20);<br>
		out(0xA1, 0x28);</h5>

	<h2>The third ICW is also quite easy to understand. The two PICs are connected to each other and the third ICW simply tells the PICs, how they are connected to each other. A standard way is connecting IRQ2 (bit 2) on PIC1 with IRQ9 (bit 1) on PIC2. Not even sure if this <i>can</i> be changed on Intel's hardware...</h2>

		<h5>out(0x21, 0x4);<br>
		out(0xA1, 0x2);</h5>

	<h2>The fourth ICW is a more compicated one, like the first. The LSB should be set, because this controlls whether to operate in 8085 mode or in 8086/8088 mode and we want the later. The second bit tells the CPU if the EOF (<i>End Of Interrupt</i>) is Automatic or normal. On Intel's hardware this bit must be set to 0 (normal) and the EOF must be done via software. The following two bits, specifies if the interrupts should be buffered or not. We don't need that, so clear these two bits. After four comes five, but here's a little problem. I don't really know what this does... The documentation says "Sets Special fully-nested mode" and I have absolutely <i>no</i> clue what that means. A standard way seems to be 0, and that works for us. The last three bits are reserved, just like in ICW1. That sums up to:</h2>

		<h5>out(0x21, 0x1);<br>
		out(0xA1, 0x1);</h5>

	<h2>There... finally done with the ICWs! Now for the masking. Masking is like a filter to turn interrupts on and off. The masking looks like this:<br><br>

	<table border=1>
		<tr>
			<th>PIC 1</th><th>PIC 2</th>
		</tr><tr>
			<td><table border=1 width=270>
				<tr>
					<th>Bit</th><th width=230>Interrupt to mask</th>
				</tr><tr>
					<td align="center">0</td><td>System Timer</td>
				</tr><tr>
					<td align="center">1</td><td>Keyboard</td>
				</tr><tr>
					<td align="center">2</td><td>Redirect to IRQ9 (PIC2)</td>
				</tr><tr>
					<td align="center">3</td><td>Serial Port 1 (COM2/4)</td>
				</tr><tr>
					<td align="center">4</td><td>Serial Port 2 (COM1/3)</td>
				</tr><tr>
					<td align="center">5</td><td>Sound Card</td>
				</tr><tr>
					<td align="center">6</td><td>Floppy Disk</td>
				</tr><tr>
					<td align="center">7</td><td>Parallell Port</td>
				</tr>
			</table></td>

			<td><table border=1 width=270>
				<tr>
					<th>Bit</th><th width=230>Interrupt to mask</th>
				</tr><tr>
					<td align="center">0</td><td>Real-Time Clock</td>
				</tr><tr>
					<td align="center">1</td><td>Redirect from IRQ2 (PIC1)</td>
				</tr><tr>
					<td align="center">2</td><td>Reserved</td>
				</tr><tr>
					<td align="center">3</td><td>Reserved</td>
				</tr><tr>
					<td align="center">4</td><td>PS/2 Mouse</td>
				</tr><tr>
					<td align="center">5</td><td>Math Co-Processor</td>
				</tr><tr>
					<td align="center">6</td><td>Hard Disk</td>
				</tr><tr>
					<td align="center">7</td><td>Reserved</td>
				</tr>
			</table></td>
		</tr>
	</table><br><br>

	A set bit in the mask, tells the CPU to skip the interrupt. The only interrupt we need is the keyboard interrupt. It's enabled through bit 1 on PIC1. <i><b>Note:</b> When disabling IRQ2 on PIC1, the entire PIC2 is disabled through the master<->slave relationship!</i></h2>

		<h5>out(0x21, 0xFD);<br>
		out(0xA1, 0xFF);</h5>

	<h2>An entry in the IDT is 64 bits long. The first 16 bits are the lower 16 bits of a 32 bit offset (address to the interrupt routine). The next 16 bits tells the CPU what segment the offset refers to (gdt_interrupt in our case and that converts to offset 0x18 in the GDT). This is where one of the help variables come in. The interrupt routine's address needs to be converted to a long variable and it's stored in this help variable for easy access.</h2>

		<h5>keyb_address = (unsigned long)keyb_int;<br>
		idt[0x21].dword0 = (keyb_address & 0xFFFF) | (0x18 << 16);</h5>

	<h2><i>Hold your horses there mister! You can't just set interrupt 0x21 and ignore the rest?!</i> Well, that's exactly what you can. There's an enable flag for every interrupt and since we haven't set any bits, the other interrupts are just ignored!<br><br>

	Bits 32-63 begins with 5 reserved bits and 3 bits that should always be set to 0 (yeah, I know it sounds silly, but just set them all to 0).<br><br>

	The following two bits decides whether the entry is an interrupt gate, a trap gate or a task gate. We can say that it <i>isn't</i> a task gate, that's for sure. So, is it an interrupt gate or a trap gate and what's the diffecence? It sounds like it should be an interrupt gate and that's the correct answer. The only real thing that seperates the two are the way they handle the <i>IF</i>, or the <i>Interrupt Flag</i>. If this is set, interrupts are enabled and otherwice, disabled. Interrupts wants to work alone, so the IF should not be set. This is represented by 10 (acually it's 01, but usually, you put the least significant bit at the far left).<br><br>

	All this is followed by a set bit and the bit after that should also be set, because it decides whether the gate is a 16 bit gate or a 32 bit gate and I wish that you find that answer rather obvious. After another 0, there are two bits that's called <i>DPL</i> or the <i>Descriptor Privilege Level</i>. As the name tell us, it has something to do with privilege or in this case security. This is the ring level from where the interrupt can be called. There are four different security levels in the Protected Mode, but I'll talk about it in a later tutorial. Just put 00 here at the moment.<br><br>

	The last bit before the last 16 bits of the offset, is called the <i>Present flag</i>. This should always be set, to let the IDT know that here's an active entry. Sum all the bits and we get 0x8E in hex. This was a long non-coding section I just wrote, but I hope you are still with me.</h2>

		<h5>idt[0x21].dword1 = (keyb_address & 0xFFFF0000) | 0x8E00;</h5>

	<h2>With that done, all we need to do is to let the CPU know where our IDT is located. Here's where our second help variable comes in to play.</h2>

		<h5>idt_address = (unsigned long)idt;</h5>

	<h2>The IDT descriptor is rather simple to understand. No strange bits to set here :). It's actually very similar to the LGDT (used to load the GDT). First we have the size or limit of the IDT which I set to 256 (max) multiplied by the size of the struct which is two longs, 8 bytes. After this 16 bits, the address of the IDT descriptor is specified. As you might have noticed, the entry is just 48 bits long, the last 16 bits are ignored.</h2>

		<h5>idt_desc[0] = 0x800 + ((idt_address & 0xFFFF) << 16);<br>
		idt_desc[1] = idt_address >> 16;</h5>

	<h2>For our next trick, we must use our little assembly knowledge. We need to execute the command LIDT to load the IDT, and execute STI to enable interrupts (which was disabled in the boot sector). A couple of NOPs is needed to ensure that the CPU has time to actually</h2>

		<h5>asm("lidt %0\n"<br></h5>
			<h6>"sti"<br>
			:"=m"(idt_desc));</h6>

	<h2>Phew! Finally! That leaves just one thing left - the interrupt it self :). Again create a new file. I call mine <i>keyb.asm</i>. <i>Hey! Wasn't we suppose to code in C the rest of the time?!</i> Well, almost. Normally, we would look in a table and jump to a C routine in this routine, but since we only have one small interrupt, we will make it 'inline'.</h2><br>

	<h2 class="header">Oh no! Not more assembly!</h2>

	<h2>The file contains 32-bit code and a function that should be accessible from outside this file called keyb_int().</h2>

	<h4>[BITS 32]<br><br>

	[GLOBAL _keyb_int]<br><br>

	[SECTION .text]<br><br>

	_keyb_int:</h4>

	<h2>The first thing in our interrupt should be to read the input buffer from the keyboard. This is done from port 0x60. We'll save it in the <i>AL</i> register, which is the lowest 8 bits in the <i>EAX</i> register.</h2>

			<h5>in al, 0x60</h5>

	<h2>What we want our interrupt to do, is to print numbers we type on the keyboard. The codes returned from the keyboard is called <i>Scan Codes</i>. These codes are different depending on the country the keyboard was made in.<br><br>

	There are also variants, but those are software controlled. We'll use US standard scan codes. Often, numbers' scan codes are the same even if your keyboard is made in a different country. The first scan code 0x1 is ESC. After that follows the numbers, so '1' has scan code 0x2, etc.<br><br>

	We just want to write those numbers, so we'll make two if statements in our code (weee, more assembly!). The first one checks if the scan code is greater than 10 and the other one if the scan code is less than 2.</h2>

			<h5>cmp al, 10<br>
			jg .return<br><br>

			cmp al, 2<br>
			jl .return</h5>

	<h2>We'll define the <i>return</i> section later. The '.' just tells the compiler that it is a local address.<br><br>

	To be able to print the scan code, we need to convert it to standard ASCII. This is simply done by adding 47 to the scan code. The ASCII number for '1' is 49 and since the scan code for '1' was 0x2, only 47 needs to be added.</h2>

			<h5>add al, 47</h5>

	<h2>We choose a static position to print our number, memory address: 0xB8000 (upper left corner like in the previous tutorial). Since the AL register contains the ASCII code, we simply move the contents to the memory address:</h2>

			<h5>mov [0xB8000], al</h5>

	<h2>Our goal is reached, we printed the character we typed on the keyboard in the upper left corner of the screen. Now for the EOF and return. Since the interrupt we received were located on PIC1, we just need to send 0x20 to port 0x20. If the interrupt have been located on PIC2, then we would need to send 0x20 to both port 0xA0 (slave) and 0x20 (master).</h2>

		<h4>.return:</h4>
			<h5>mov al, 0x20<br>
			out 0x20, al</h5>

	<h2>If this was a normal funtion, we would have used RET to return, but since this is an interrupt we have to use IRET. The difference is that IRET also saves a bunch of registers which RET doesn't (they use them for parameters instead). This is one of the reasons C isn't very good to write pure interrupt functions, because they use RET.</h2>

			<h5>iret</h5><br><br>

	<h2>The only thing left is the compiling part! First the boot sector to plain binary. Then our interrupt routine, but it should be linked together with the rest of the kernel, so we use the coff format when compiling.</h2>

		<h4>nasm -f bin bootsect.asm -o bootsect.bin<br>
		nasm -f coff keyb.asm -o keyb.o</h4>

		<h4>gcc -ffreestanding -c main.c -o main.o<br>
		gcc -c video.c -o video.o<br>
		gcc -c ports.c -o ports.o<br>
		gcc -c ints.c -o ints.o<br>
		ld -e _main -Ttext 0x0 -o kernel.o main.o video.o ports.o keyb.o ints.o<br>
		ld -i -e _main -Ttext 0x0 -o kernel.o main.o video.o ports.o keyb.o ints.o<br>
		objcopy -R .note -R .comment -S -O binary kernel.o kernel.bin</h4>

	<h2>Use some program to put the files together. If you use my <i>makeboot</i> program, the syntax is the same as the previous tutorial:</h2>

		<h4>makeboot a.img bootsect.bin kernel.bin</h4>

	<h2>If you are a Windows user, you can use plain old copy to do the trick!</h2>

		<h4>copy /b bootsect.bin +kernel.bin a.img</h4>


	<h2>Just run Bochs with a.img and this is what you should get when you press '1' on your keyboard:<br>

	<img src="bochs_responding_to_keyboard.html"><br><br>

	<a href="tutor4.html">Download</a> the complete source for this tutorial, including makeboot and a .bat-file for compiling.<br><br>
	<a href="../tutorial_01/bochsrc.html">Download</a> my example configuration file for Bochs 2.0.2 - Win32.<br><br>
	<a href="../tutorial_01/bochsrc-2.html">Download</a> my example configuration file for Bochs (paths to the BIOS may have to be changed, if you're using another distributions than Win32 1.4.1).<br><br>

Any comments, improvments or found errors? Mail me: <a href="mailto:gregor.brunmar@home.se">gregor.brunmar@home.se</a>.</h2>

	<table class="links" width=100%><tr>
		<td align=left>Move back to <a href="../tutorial_03/tutorial_03.html">tutorial 3</a></td>
		<td align=right>Move on to tutorial 5</a></td>
	</tr></table><br>
</body>

<!-- Mirrored from bos.asmhackers.net/docs/booting/docs/tutorial_04.htm by HTTrack Website Copier/3.x [XR&CO'2013], Tue, 07 Oct 2014 11:22:02 GMT -->
</html>
